package com.shiwei.is;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.shiwei.is.tools.Helper;
import com.shiwei.is.transmission.ImageSender;
import com.shiwei.is.view.VideoFeedView;
import com.squareup.otto.Subscribe;

import dji.sdk.camera.VideoFeeder;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "ISApp-MainActivity";
    private VideoFeedView primaryFeedView;
    private VideoFeedView secondaryFeedView;
    private ImageSender imageSender;
    private Button mSwitch;
    private ImageButton mStartBtn;
    private boolean isStarted = false;
    private boolean isPrimary = true;
    private VideoFeeder.VideoDataListener videoDataListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ISApplication.getEventBus().register(this);

        setContentView(R.layout.activity_main);

        initUI();
        initAction();
        initReceiver();
    }

    private void initUI(){
        primaryFeedView = findViewById(R.id.primary_video_feed);
        secondaryFeedView = findViewById(R.id.secondary_video_feed);
        View feedCover = findViewById(R.id.video_cover);
        primaryFeedView.setCoverView(feedCover);
        feedCover = findViewById(R.id.video_cover2);
        secondaryFeedView.setCoverView(feedCover);

        mSwitch = findViewById(R.id.switch_video);
        mStartBtn = findViewById(R.id.start_sender);
        Glide.with(this).asBitmap()
                .load(R.drawable.sending)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(mStartBtn);
    }

    private void initAction() {
        imageSender = new ImageSender(this);
        primaryFeedView.setImageSender(imageSender);
        primaryFeedView.registerLiveVideo(VideoFeeder.getInstance().getPrimaryVideoFeed(), true);
        secondaryFeedView.registerLiveVideo(VideoFeeder.getInstance().getSecondaryVideoFeed(), false);
        findViewById(R.id.set_url).setOnClickListener(view -> showSettingDlg());
        mStartBtn.setOnClickListener(view -> doSender(!isStarted));
        mSwitch.setOnClickListener( view -> doSwitch(!isPrimary));
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("dji_sdk_source_change");
        registerReceiver(receiver, filter);
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            runOnUiThread(() -> doSwitch(true));
        }
    };

    private void doSender(boolean toStart) {
        this.isStarted = toStart;
        if(isStarted) {
            imageSender.startSend();
            Glide.with(this).asGif()
                    .load(R.drawable.sending)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .into(mStartBtn);
        } else {
            imageSender.endSend();
            Glide.with(this).asBitmap()
                    .load(R.drawable.sending)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .into(mStartBtn);
        }
    }

    private void doSwitch(boolean isPrimary) {
        this.isPrimary = isPrimary;
        doSender(false);
        if(isPrimary) {
            findViewById(R.id.primary).setVisibility(View.VISIBLE);
            findViewById(R.id.secondary).setVisibility(View.GONE);
            primaryFeedView.setImageSender(imageSender);
            secondaryFeedView.setImageSender(null);
            mSwitch.setText(R.string.change_to_fpv);
        } else {
            findViewById(R.id.primary).setVisibility(View.GONE);
            findViewById(R.id.secondary).setVisibility(View.VISIBLE);
            primaryFeedView.setImageSender(null);
            secondaryFeedView.setImageSender(imageSender);
            mSwitch.setText(R.string.change_to_primary);
        }
    }

    private void showSettingDlg() {
        View view = getLayoutInflater().inflate(R.layout.dialog_setting, null);
        EditText et_address = view.findViewById(R.id.tv_address);
        EditText et_pwd = view.findViewById(R.id.tv_pwd);
        new AlertDialog.Builder(this)
                .setView(view)
                .setPositiveButton(android.R.string.ok, (dlg, pos) -> {
                    String address = et_address.getText().toString();
                    String pwd = et_pwd.getText().toString();
                    if(!address.startsWith("ws://")) {
                        showToast("Invalid address");
                    } else if(pwd.isEmpty() || pwd.trim().length() < 6) {
                        showToast("Token is needed with len >= 6");
                    } else {
                        Helper.setWebSocketUrl(MainActivity.this, address.trim());
                        Helper.saveUserToken(MainActivity.this, pwd.trim());
                        if(isStarted){
                            imageSender.reStartWebSocket();
                        }
                    }
                })
                .create().show();
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show());
    }

    @Subscribe
    public void onConnectivityChange(ConnectivityChangeEvent event) {
        Log.d(TAG, "event:" + event);
        showToast("event:" + event);
    }

    @Override
    protected void onDestroy() {
        ISApplication.getEventBus().unregister(this);
        imageSender.endSend();
        primaryFeedView.setImageSender(null);
        secondaryFeedView.setImageSender(null);

        super.onDestroy();
    }

    public static class ConnectivityChangeEvent {
    }
}